//
//  UserAccountViewModel.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/6.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import Foundation
class UserAccountViewModel{
/// 用户属性
    var userAccount:UserAccount?
/// 用户头像大图
    var avatarUrl:NSURL {
        return NSURL(string: userAccount?.avatar_large ?? "")!
    }
/// 归档保存路径
    var accountPath:String{
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("userAccount.plist")
    }
/// 判断是否过期
    private var isExpired:Bool{
        if userAccount?.expirseDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            return false
        }
        return true
    }
    
/// 用户登录标记

    var userLogin:Bool{
        return (userAccount?.access_token != nil) && !isExpired
    }
/// 用户视图单例
    static let sharedUserAccount = UserAccountViewModel.init()
/// 返回 token
    var accessToken:String?{
        if !isExpired{
            return userAccount?.access_token
        }
        return nil
    }
/// MARK: - 构造函数
private init(){
    /// 从沙盒加载用户信息
    userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
    //        判断账号是否过期
    if isExpired{
        userAccount = nil
    }
}
}

extension UserAccountViewModel{
    func loadAccessToke(code:String, finished:(isSuccessed:Bool) -> ()){
       NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> ()
        in
//        1 判断错误
        if error != nil{
            finished(isSuccessed: false)
            return
        }
//        2 记录账户属性
        self.userAccount = UserAccount(dict:result as! [String:AnyObject])
//        3 记载账户属性
        self.loadUserInfo(self.userAccount!, finished: finished)
        }
    }
    
    private func loadUserInfo(account:UserAccount,finished:(isSuccessed:Bool) -> ()){
        NetWorkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            
            if (error != nil) {
             finished(isSuccessed: false)
             return
            }
            guard let dict = result as?[String:AnyObject] else {
                return
            }
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            finished(isSuccessed: true)
        }
    }

}